#include "xmlwriter.h"
#include "messagedisplay.h"

XmlWriter::XmlWriter(const QString &fileName):
        m_file(fileName),
       m_indent(0)
{
    /* Ensure that the file was successfully loaded. */
    if(!m_file.open(QIODevice::WriteOnly | QIODevice::Text))
        (new MessageDisplay("There was an error creating the file",
                           "Parser File Error"))->show();

    m_file.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n");
}

void XmlWriter::writeObject(const QString& object) {

    QString writeText(indent());

    ++m_indent;

    writeText.append("<");
    writeText.append(object);
    writeText.append(">");
    writeText.append("\n");

    m_file.write(writeText.toAscii());
}

void XmlWriter::closeObject(const QString& object) {

    --m_indent;

    QString writeText(indent());

    writeText.append("</");
    writeText.append(object);
    writeText.append(">");
    writeText.append("\n");

    m_file.write(writeText.toAscii());
}

void XmlWriter::writeAttribute(const QString& attribute,
                               const QString& value) {

    QString writeText(indent());

    writeText.append("<");
    writeText.append(attribute);
    writeText.append(">");
    writeText.append(value);
    writeText.append("</");
    writeText.append(attribute);
    writeText.append(">");
    writeText.append("\n");

    m_file.write(writeText.toAscii());
}

QString XmlWriter::indent() {

    QString indent;

    for( int i = 0; i < m_indent; ++i )
        indent.append("\t");

    return indent;

}
